import React, { useEffect, useState } from 'react'
import ShowDrawer from '@/components/ShowDrawer'
import {
    Form,
    Input,
    Select,
    List,
    InputNumber,
    Radio,
    TreeSelect,
    message,
    Switch
} from 'antd';
import { rules } from './rules'
import { IUser } from '../types';
import deptApi from '@/api/system/dept'
import roleApi from '@/api/system/role'
import { IRole } from '../../role/types';
import { addInfo,updateInfo } from '@/api/system/user';
import { connect } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { removeAll } from '@/utils/session';

function Info(props: any) {
    let { info,userInfo } = props;
    let fieldNames = {
        label: 'deptName',
        value: 'deptName',
        children: 'children',
    }
    //初始化表单
    let initForm = {
        userName: '',
        userPassword: '123456',
        telephone: '',
        email: '',
        roleName: undefined,
        deptName: undefined,
        status: 1
    }
    const navigate = useNavigate()
    const [form] = Form.useForm<IUser>();
    const [infoForm, setInfoForm] = useState<IUser>({ ...initForm, ...info });
    const [deptList,setDeptList] = useState<Array<object>>([])
    const [roleList,setRoleList] = useState<Array<IRole>>([])

    useEffect(()=>{
        getDeptList();
        getRoleList();
    },[]);

    //提交表单
    const onFinish = async () => {
        form.validateFields().then(async values => {
            let info = {...infoForm,...values};
            let {status} = info;
            if(status===true){
                info.status=1
            }
            if(status===false){
                info.status=0
            }
            if (info.userId) {
                delete info.userPassword;
                await updateInfo(info);
                if(info.userId==userInfo.userId){
                    removeAll()
                    navigate('/login')
                }
            } else {
                await addInfo(info);
            }
            message.success('操作成功');
            form.resetFields();
            props.submit();
        }).catch(info => {
            console.log('Validate Failed - ', info);
        });
    }
    //获取角色列表
    const getRoleList = async ()=>{
        try{
            let res = await roleApi.remoteList({page:1,size:50});
            let {list} = res.data;
            setRoleList(list);
        }finally{}
    }
    //获取部门列表
    const getDeptList = async()=>{
        try{
            let res = await deptApi.remoteList({});
            let {data} = res;
            setDeptList(data);
        }finally{}
    }

    return (
        <ShowDrawer
            title="用户信息"
            close={() => props.close()}
            submit={() => onFinish()}>
            <Form
                form={form}
                name="info"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                initialValues={{ remember: false }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item label="用户名" initialValue={infoForm.userName} name="userName" rules={rules.userName}>
                    <Input placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item label="手机号" initialValue={infoForm.telephone} name="telephone" rules={rules.telephone}>
                    <Input placeholder="请输入手机号" />
                </Form.Item>
                <Form.Item label="邮箱" initialValue={infoForm.email} name="email" rules={rules.email}>
                    <Input placeholder="请输入邮箱" />
                </Form.Item>
                <Form.Item label="用户角色" initialValue={infoForm.roleName} name="roleName" rules={rules.roleName}>
                    <Select placeholder="请选择用户角色">
                        {
                            roleList.map(item=><Select.Option key={item.roleId} value={item.roleName}>{item.roleName}</Select.Option>)
                        }
                    </Select>
                </Form.Item>
                <Form.Item label="部门" initialValue={infoForm.deptName} name="deptName" rules={rules.deptName}>
                    <TreeSelect
                        style={{ width: '100%' }}
                        value={infoForm.deptName}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择部门"
                        allowClear
                        treeData={deptList}
                        fieldNames={fieldNames} />
                </Form.Item>
                {
                    !infoForm.userId && (<Form.Item label="初始密码" initialValue={infoForm.userPassword} name="userPassword">
                        <Input className='form_item' disabled placeholder="请输入初始密码" />
                    </Form.Item>)
                }
                <Form.Item label="状态" valuePropName='status' name="status">
                    <Switch defaultChecked={infoForm.status==1?true:false} checkedChildren="开启" unCheckedChildren="关闭"/>
                </Form.Item>

            </Form>
        </ShowDrawer>
    )
}

const mapStateToProps = (state: { Global: { userInfo: any; }; }) => {
    return {
        userInfo: state.Global.userInfo
    }
}
export default connect(mapStateToProps)(Info)
